﻿using System;
using System.Linq;
using System.Data.Objects;

namespace RakutenCrawler.Repository
{
    public abstract class GenericRepository<T> : IDisposable where T : class
    {
        protected RakutenEntities _context;
        public ObjectSet<T> All
        {
            get { return _context.CreateObjectSet<T>(); }
        }

        public abstract void InsertOrUpdate(T item);

        public void Delete(T item)
        {
            All.DeleteObject(item);
        }

        public IQueryable<T> FindBy(System.Linq.Expressions.Expression<Func<T, bool>> predicate)
        {
            IQueryable<T> query = All.Where(predicate);
            return query;
        }

        public T Single(System.Linq.Expressions.Expression<Func<T, bool>> predicate)
        {
            T result = All.FirstOrDefault(predicate);
            return result;
        }

        public GenericRepository(bool lazyLoadingEnabled = false, bool proxyCreation = true)
        {
            _context = new RakutenEntities();
            _context.ContextOptions.LazyLoadingEnabled = lazyLoadingEnabled;
            _context.ContextOptions.ProxyCreationEnabled = proxyCreation;
        }

        public void Save()
        {
            _context.SaveChanges();
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (_context != null)
                {
                    _context.Dispose();
                    _context = null;
                }
            }
        }
    }
}
